<template>
    <div>
      <!--三级分类相关的卡片-->
      <el-card class="box-card" style="margin: 10px">
        <CategorySelector @change="changeFn" :disabled="!showList"></CategorySelector>
      </el-card>

      <!--查询操作对应的区域-->
      <el-card v-show="showList">
        <el-button  type="primary" :disabled="!category3Id"
                    icon="el-icon-circle-plus" size="small"
                    @click="toAddInterface">
          添加属性
        </el-button>
        <el-table
          v-loading.fullscreen.lock="loading"
          element-loading-text="拼命加载中"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.8)"
          border :data="tableData" style="margin-top: 10px">
          <el-table-column type="index" label="序号" width="80" align="center"></el-table-column>
          <el-table-column label="属性名称" width="180" prop="attrName"
                           align="center"></el-table-column>
          <el-table-column label="属性值列表">
            <template slot-scope="{row}">
              <el-tag type="info" style="margin-right: 2px" :key="attrValue.id"
                      v-for="attrValue in row.attrValueList">
                {{attrValue.valueName}}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" align="center">
            <template slot-scope="{row,$index}">
              <el-tooltip class="item" effect="dark" content="编辑" placement="top-start">
                <el-button type="primary" size="mini"
                           icon="el-icon-edit" @click="toEditInterface(row)">
                </el-button>
              </el-tooltip>
              <el-popconfirm :title="`确定删除 ${row.attrName} 吗?`" @onConfirm="delAttr(row.id)">
                <el-tooltip slot="reference" class="item" effect="dark" content="删除" placement="top-start">
                  <el-button type="danger" size="mini" icon="el-icon-delete">
                  </el-button>
                </el-tooltip>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!--新增&修改操作对应的区域-->
      <el-card v-show="!showList">
        <el-form label-width="60px">
          <el-form-item label="属性名">
            <el-input placeholder="请输入属性名" v-model="attr.attrName"
                      style="width: 200px"></el-input>
          </el-form-item>
        </el-form>

        <el-button type="primary" icon="el-icon-plus"
                   @click="addAttrVal"
                   :disabled="!attr.attrName.trim()">添加属性值</el-button>
        <el-button @click="cancel">取消</el-button>

        <el-table :data="attr.attrValList" border style="margin-top: 15px">
          <el-table-column type="index" label="序号"
                           width="100px" align="center"></el-table-column>
          <el-table-column label="属性名称">
            <template slot-scope="{row,$index}">
              <div v-if="!row.isEdit" @dblclick="show2edit(row,$index)">
                {{row.valName}}
              </div>
              <el-input v-else v-model.trim="row.valName"
                        :ref="`input-${$index}`"
                        @keydown.13.native="edit2show(row,$index)"
                        @blur="edit2show(row,$index)">
              </el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <!--<el-popconfirm title="这是一段内容确定删除吗？">

            </el-popconfirm>-->

            <template slot-scope="{row,$index}">
              <el-popconfirm title="这是一段内容确定删除吗？"
                             @onConfirm="delAttrVal($index)">
                <el-tooltip slot="reference" class="item" effect="dark"
                          content="刪除" placement="top">
                  <el-button type="danger" size="mini"
                             :disabled="saveDisabled"
                             icon="el-icon-delete">
                  </el-button>
                </el-tooltip>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>

        <el-button type="primary" :disabled="saveDisabled"
                   @click="saveFn">保存</el-button>
        <el-button @click="cancel">取消</el-button>


      </el-card>
    </div>
</template>

<script>
    export default {
        name: "attrList",
        data(){
          return {
            tableData:[],//属性列表数据
            category1Id:"",
            category2Id:"",
            category3Id:"",
            loading:false, //控制表格的loading状态
            showList:true, //是否显示显示列表
            attr:{
              attrName:"",
              attrValList:[] //[{valName:"红色",isEdit:true},{valName:"粉色"}....]
            },
            dog3:false//代表属性值是否不合法  false:合法
          }
        },
        computed:{
          //控制保存按钮的禁用状态的
          saveDisabled(){
            //在属性名没有值 或 属性值数组为空时要禁用
            const flag1 = this.attr.attrName.trim() ==="" || this.attr.attrValList.length===0;
            let flag2 = false;
            //在属性值不合法時也要禁用
            const row = this.attr.attrValList[this.attr.attrValList.length-1];
            if(row){
              const dog1 = row.valName.trim() === "";
              const num = this.attr.attrValList.filter((item)=>{
                return item.valName === row.valName
              }).length;
              const dog2 = num >= 2;
              flag2 = dog1 || dog2;
            }else{
              flag2 = false;
            }
            return flag1 || flag2;
          }
        },
        methods:{
          //属性的CRUD操作
          async saveFn(){
            //读id 有id是修改 没id新增
            const {id} = this.row;
            //发送新增的请求
            const attrInfo = {
              attrName:this.attr.attrName,
              attrValueList:
                this.attr.attrValList.map(({valName}) => ({valueName:valName})),
              categoryId: this.category3Id,
              categoryLevel: 3,
              id
            }
            await this.$API.product.attr.saveAttrInfo(attrInfo);
            //关闭新增的界面
            this.showList = true;
            //重新获取数据
            await this.getAttrList()
          },
          async delAttr(id){
            await this.$API.product.attr.deleteAttr(id);
            this.$message.success("删除成功");
            //重新获取数据
            await this.getAttrList()
          },
          //显示编辑界面
          toEditInterface(row){
            //携带属性信息去saveFn方法
            this.row = row;
            //表单回显
            this.attr.attrName = row.attrName;
            this.attr.attrValList =
              row.attrValueList.map(({valueName})=>({valName:valueName}))
            //打开界面
            this.showList = false;
          },
          //显示新增界面
          toAddInterface(){
            //清空row
            this.row={}
            //清空表单
            this.attr={
              attrName:"",
              attrValList:[]
            }
            //打开界面
            this.showList = false;
          },


          //属性值的CRUD操作
          //删除属性值
          delAttrVal(index){
            this.attr.attrValList.splice(index,1)
          },
          //修改属性值 当双击属性值文本时 从显示状态变为编辑状态
          show2edit(row,index){
            if(this.dog3){
              //代表上一次的属性值的输入有问题
              return
            }
            //row:当前属性值对象
            // row.isEdit = true;
            if(row.hasOwnProperty("isEdit")){
              row.isEdit = true
            }else{
              this.$set(row,"isEdit",true)
            }
            //获取焦点
            this.$nextTick(()=>{
              this.$refs[`input-${index}`].focus()
            })
          },
          //添加属性值
          addAttrVal(){
            if(this.dog3){
              //代表上一次的属性值的输入有问题
              return
            }

            //组装属性值对象
            const attrVal = {valName:"",isEdit:true}
            //塞入到attrValList中
            this.attr.attrValList.push(attrVal)
            //让最新的输入框获取焦点
            this.$nextTick(()=>{
              this.$refs[`input-${this.attr.attrValList.length-1}`].focus()
            })
          },
          //添加属性值 属性值对应的输入框 从编辑状态变为显示状态
          edit2show(row,index){
            //当属性值为空的时候 不允许切换为显示状态
            const dog1 = row.valName.trim() === "";
            if(dog1){
               //同步dog1的状态
               this.dog3 = dog1;
               //错误提醒
               this.$message.closeAll();
               this.$message.error({
                 message:"属性值不能为空",
                 duration:2000
               })
               //重新获取焦点
               this.$refs[`input-${index}`].focus()
               return;
            }
            //当属性值重复时 不允许切换为显示状态
            const num =
              this.attr.attrValList.filter((item)=>{
                return item.valName === row.valName
              }).length;
            const dog2 = num >= 2;
            if(dog2){
              //同步dog1的状态
              this.dog3 = dog2;
              //错误提醒
              this.$message.closeAll();
              this.$message.error({
                message:"属性值不能重复",
                duration:2000
              })
              //重新获取焦点
              this.$refs[`input-${index}`].focus()
              return;
            }
            //切为显示状态
            //row : 当前属性值对应的对象
            this.dog3 = false;
            row.isEdit = false;
          },
          //取消按钮逻辑
          cancel(){
            if(this.dog3){
              //代表上一次的属性值的输入有问题
              return
            }
            this.showList=true;
          },



          //当三级分类中任意一级分类 产生改变时触发
          async changeFn({level,value}){
            console.log(value);
            switch (level){
              case 1:
                //清空 23级分类的内容
                this.tableData = [];
                this.category2Id="",
                this.category3Id="",
                //重置1级分类
                this.category1Id = value;
                break;
              case 2:
                //清空3级分类的内容
                this.tableData = [];
                this.category3Id="",
                //重置2级分类
                this.category2Id = value;
                break;
              case 3:
                this.category3Id = value;
                //发送请求获取属性列表
                await this.getAttrList()
                break;
            }
          },
          //发送请求获取对应三级分类的属性
          async getAttrList(){
            this.loading = true;
            const {category1Id,category2Id,category3Id} = this;
            const {data} = await this.$API.product.attr.getAttrList({
              category1Id, category2Id, category3Id
            });
            this.tableData = data;
            this.loading = false;
          }
        }
    }
</script>

<style lang="less">
  .box {
    width: 400px;

    .top {
      text-align: center;
    }

    .left {
      float: left;
      width: 60px;
    }

    .right {
      float: right;
      width: 60px;
    }

    .bottom {
      clear: both;
      text-align: center;
    }

    .item {
      margin: 4px;
    }

    .left .el-tooltip__popper,
    .right .el-tooltip__popper {
      padding: 8px 10px;
    }
  }
</style>
